$(function () {
    // console.log('????');

    $('#keyword').on('keyup', function () {
        var keyword = $(this).val();
        console.log(keyword);
        if (keyword !== '' && keyword !== null) {
            $.ajax({
                // type:'POST',
                type: 'GET',
                // url:'http://localhost:8080/jpetstore_666/productAuto?keyword='+keyword,
                url: 'http://localhost:8080/catalog/productAuto?keyword=' + keyword,
                success: function (data) {

                    //console.log(data);
                    var productListHTML = '';
                    for (var i = 0; i < data.length; i++) {
                        productListHTML += '<li class="productAutoItem" data-productId="';
                        productListHTML += data[i].productid;
                        productListHTML += '">';
                        productListHTML += data[i].category;
                        productListHTML += ': ';
                        productListHTML += data[i].name;
                        productListHTML += '</li>';
                    }
                    $('#productAutoList').html(productListHTML);
                    $('#productAutoComplete').show();
                },
                error: function (errorMsg) {
                    console.log(errorMsg);
                }
            })
        } else {
            $('#productAutoComplete').hide();
        }
    });
    var elSearch=document.getElementById('keyword');
    var elSearchMsg=document.getElementById('keywordsAvailability');
    var elButtonSearch=document.getElementById('button-search');
    var isSearchClicked = false; // 添加一个标记变量来跟踪搜索按钮是否被点击过
    // elButtonSearch.addEventListener('click', function() {
    //     elSearch.focus();
    //     isSearchClicked = true;
    //     checkSearch(elSearch.value);
    //
    // });
    elSearch.addEventListener('blur',function (){
        elSearchMsg.textContent='';
    });
    elSearch.addEventListener('focus',function (){
        elSearchMsg.textContent='Please input the keywords';
        //elSearchMsg.style.color="red";
    })

    // function checkSearch(keywords){
    //     if(keywords===null||keywords===''){
    //         elSearchMsg.textContent='请输入关键字';
    //         elSearchMsg.style.color="red";
    //     }else{
    //         elSearchMsg.textContent='';
    //     }
    // }

    // $(document).on('click','.productAutoItem',function (){
    //
    // })动态加载，这样写无法绑定，因为运行到这里时productAutoItem不一定已经加载

    $(document).on('click', '.productAutoItem', function () {
        console.log('111111');
        var productId = $(this).data('productid');
        console.log(productId);
        $('#productAutoComplete').hide();
        $('#keyword').val('');
        window.location.href = 'http://localhost:8080/catalog/viewProduct?productId=' + productId;

    })

    $('#productAutoComplete').on('mouseleave', function () {
        $(this).hide();
        $('#keyword').val('');
    })
})